package com.godyao.framework.beans.factory.support;

import com.godyao.framework.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * Cglig实现
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
//        enhancer.setCallback(new MethodInterceptor() {
//            @Override
//            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
//                Object res;
//                System.out.println("前");
//                res = proxy.invokeSuper(obj, args);
////                res = method.invoke(args);
//                System.out.println("后");
//                return res;
//            }
//        });
        if (null == constructor) {
            return enhancer.create();
        }
        return enhancer.create(constructor.getParameterTypes(), args);
    }
}
